#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import sys
import argparse
import pygraphviz as pgv

from ctools.common.strhelper import *

from .fworkerbase import *

import logging
from ctools.logext import *

_rlog, _plog, _mlog, _tlog = get_loggers(__file__, __name__, propagate=False)

_fpath = os.path.dirname(os.path.realpath(__file__))
_rcs_path = os.path.join(_fpath, '../rcs')

jar_file = 'plantuml-lgpl-1.2024.7.jar'

class PUmlFileHandler(FileWorkerBase):
    '''
    https://plantuml.com/zh/
    apt install openjdk-17-jre
    Usage: java -jar plantuml.jar -help
    '''

    @classmethod
    def is_match(cls, filename):
        if filename.endswith('.puml'):
            return True
        if filename.endswith('.plantuml'):
            return True
        return False

    def __init__(self, filename="", opt_str=''):
        super().__init__(filename)
        self.jpath = os.path.join(_rcs_path, jar_file)
        self.opt_str = opt_str

    def _on_modified(self):
        super()._on_modified()
        self.do_modified()

    def do_modified(self):
        try:
            cmd = f'java -jar {self.jpath} {self.opt_str} {self.filename}'
            _mlog.info(f'cmd: {cmd}')
            os.system(cmd)
        except:
            pass

    @classmethod
    def handle_new(cls, filepath:str, opts=None):
        cmd = f'touch {filepath}'
        os.system(cmd)

    @classmethod
    def _handle_remove_files(cls, filepath:str, opts=None):
        files = (
                filepath,
                new_filepath(filepath, lambda bname: new_basename(bname, ".c", ".png")),
            )
        return files

